package stack;

import org.junit.Test;

import java.util.Scanner;

//数组模拟栈
public class ArrayStackDemo {
    //数组模拟栈
   @Test
    public  void test(){
       ArrayStack arrayStack=new ArrayStack(5);
       boolean flag=true;
       Scanner sc=new Scanner(System.in);
       while (flag){
           System.out.println("show(s):展示所有栈中数据~ ~");
           System.out.println("add(a):添加数据入栈~ ~");
           System.out.println("pop(p):删除栈顶数据~ ~");
           System.out.println("exit(e):退出程序~ ~");
           System.out.print("请输入命令:");
            char c = sc.next().charAt(0);
            switch (c){
                case 's':
                    arrayStack.list();
                    break;
                case 'a':
                    System.out.print("请输入要添加的数据:");
                    int num=sc.nextInt();
                    arrayStack.push(num);
                    break;
                case 'p':
                    try {
                        System.out.println("出栈的数据是:"+arrayStack.pop());
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    flag=false;
                    break;
                default:
                    break;
            }
       }
       System.out.println("成功退出程序~ ~");
   }

    //链表模拟栈
    @Test
    public void testLink(){

    }

}

//todo 链表模拟栈
class ArrayLinkedListStack{
    LinkStack headStack=new LinkStack();

}
class LinkStack{
    private int index;
    private LinkStack next;
}


//数组模拟栈
class ArrayStack{

    private int maxSize;//栈的最大值
    private int top=-1; //栈指向
    private int[] stack;//模拟栈数组

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack=new int[maxSize];
    }
    //判断栈满
    public  boolean isFull(){
        return top==maxSize-1;  //top->最顶部
    }
    //判断栈空
    public  boolean isEmpty(){
        return top==-1;
    }
    //入栈 push  往数组里添加数据  先判断栈是否满了
    public void push(int value){
        if(isFull()){
            System.out.println("栈满了~ ~");
            return;
        }
        top++;
        stack[top]=value;
    }
    //出栈 pop  先进后出   顶部先出  先判断栈是否为空
    public int pop(){
        if(isEmpty()){
            throw  new RuntimeException("栈空~ ~");
        }
        int value=stack[top];
        top--;
        return value;
    }
    //遍历栈
    public  void list(){
        //先判断栈是否为空
        if(isEmpty()){
            System.out.println("栈空~ ~");
            return;
        }
        //先进后出  从最后往前遍历
        for (int i =top; i>=0 ; i--) {
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }

}
